<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>商品参数</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片区域 -->
    <el-card>
      <!-- 警告 -->
      <el-alert title="注意: 只允许为三级分类设置" type="warning" show-icon></el-alert>
      <!-- 分类选择 -->
      <el-row :gutter="20" style="margin:15px 0 10px 0">
        <el-col :span="3" style="padding:6px 0 0 0;font-size:20px">选择商品分类</el-col>
        <el-col :span="21">
          <!-- 级联选择器 -->
          <el-cascader v-model="selectedKeys" :options="cateList" clearable @change="handleChange"
            :props="{ expandTrigger: 'hover' , label:'cat_name' , value:'cat_id'}">
          </el-cascader>
        </el-col>
      </el-row>
      <!-- tab栏 -->
      <el-tabs v-model="activeName" @tab-click="handleClick">
        <!-- 动态参数 -->
        <el-tab-pane label="动态参数" name="many">
          <el-button type="primary" :disabled='isBtnDisabled' @click="addDialogVisible=true" style="margin-bottom:15px">
            添加动态参数
          </el-button>
          <el-table :data="manyTableData" border stripe>
            <!-- 展开内容 -->
            <el-table-column label="展开" type="expand">
              <template v-slot='{row}'>
                <el-tag v-for="(item,i) in row.attr_vals" :key="i" closable @close='removeTag(row,i)'>
                  {{item}}
                </el-tag>
                <!-- 添加tag输入框 -->
                <el-input class="input-new-tag" v-if="row.inputVisible" v-model.trim="row.inputValue" ref="saveTagInput"
                  size="small" @keyup.enter.native="handleInputConfirm(row)" @blur="handleInputConfirm(row)">
                </el-input>
                <!-- 添加tag按钮 -->
                <el-button v-else class="button-new-tag" size="small" @click="showInput(row)">+ New Tag</el-button>
              </template>
            </el-table-column>
            <!-- 索引 -->
            <el-table-column label="#" type="index"></el-table-column>
            <!-- 参数名称 -->
            <el-table-column label="参数名称" prop="attr_name"></el-table-column>
            <!-- 操作按钮 -->
            <el-table-column label="操作">
              <template v-slot='{row}'>
                <!-- 编辑 -->
                <el-button type="primary" size="mini" icon="el-icon-edit" @click="showEditForm(row)"></el-button>
                <!-- 删除 -->
                <el-button type="danger" size="mini" icon="el-icon-delete" @click="removeParamsCate(row.attr_id)">
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
        <!-- 静态属性 -->
        <el-tab-pane label="静态属性" name="only">
          <el-button type="primary" :disabled='isBtnDisabled' @click="addDialogVisible=true" style="margin-bottom:15px">
            添加静态属性</el-button>
          <el-table :data="onlyTableData" border stripe>
            <el-table-column label="展开" type="expand"></el-table-column>
            <el-table-column label="#" type="index"></el-table-column>
            <el-table-column label="参数名称" prop="attr_name"></el-table-column>
            <el-table-column label="操作">
              <template v-slot='{row}'>
                <!-- 编辑 -->
                <el-button type="primary" size="mini" icon="el-icon-edit" @click="showEditForm(row)"></el-button>
                <!-- 删除 -->
                <el-button type="danger" size="mini" icon="el-icon-delete" @click="removeParamsCate(row.attr_id)">
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
      </el-tabs>
    </el-card>

    <!-- 添加 -->
    <el-dialog :title="'添加' + addFormTitleName" :visible.sync="addDialogVisible" width="50%" @close='closeAddForm'>
      <el-form :model="addForm" ref="addFormRef" :rules="addFormRules" label-width="80px">
        <el-form-item :label="addFormTitleName" prop="attr_name">
          <el-input v-model="addForm.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addParamsCate">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 修改 -->
    <el-dialog :title="'修改' + addFormTitleName" :visible.sync="editDialogVisible" width="50%" @close='closeEditForm'>
      <el-form :model="editForm" ref="editFormRef" :rules="addFormRules" label-width="80px">
        <el-form-item :label="addFormTitleName" prop="attr_name">
          <el-input v-model="editForm.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="saveEditParamsCate">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data () {
    return {
      // 修改对话框表单数据
      editForm: {
        attr_name: ''
      },
      // 修改对话框显示状态
      editDialogVisible: false,
      // 添加对话框表单规则
      addFormRules: {
        attr_name: [
          { required: true, message: '请输入参数', trigger: 'blur' }
        ]
      },
      // 添加对话框表单的数据
      addForm: {
        attr_name: ''
      },
      // 添加对话框显示状态
      addDialogVisible: false,
      // tab栏选中参数
      activeName: 'many',
      // 选中参数
      selectedKeys: [],
      // 分类数据
      cateList: [],
      // 动态参数数据
      manyTableData: [],
      // 静态属性数据
      onlyTableData: []
    }
  },
  methods: {
    // 封装 把更新后的tag上传到服务器
    async saveTags (row) {
      const { data: res } = await this.$http.put(`categories/${this.cateId}/attributes/${row.attr_id}`, { attr_name: row.attr_name, attr_sel: row.attr_sel, attr_vals: row.attr_vals.join(' ') })
      if (res.meta.status !== 200) return this.$message.error('添加tag标签失败')
      this.$message.success('添加tag标签成功')
    },
    // 删除tag标签
    removeTag (row, i) {
      row.attr_vals.splice(i, 1)
      this.saveTags(row)
    },
    // 添加tag按钮点击事件
    showInput (row) {
      row.inputVisible = true
      // 让文本框自动获取焦点
      // 在页面元素重新渲染后才会触发$nextTick
      this.$nextTick(_ => {
        // this.$refs.saveTagInput 组件
        // $refs.input DOM元素
        this.$refs.saveTagInput.$refs.input.focus()
      })
    },
    // 添加tag输入框输入enter/失去焦点触发事件
    handleInputConfirm (row) {
      // 输入框内容为空失去焦点变成按钮
      if (row.inputValue.length === 0) {
        row.inputVisible = false
        return
      }
      // 把添加的tag渲染到页面
      row.attr_vals.push(row.inputValue.trim())
      this.saveTags(row)
      row.inputValue = ''
      row.inputVisible = false
    },
    // 删除参数功能
    removeParamsCate (id) {
      this.$confirm('此操作将永久删除参数, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        const { data: res } = await this.$http.delete(`categories/${this.cateId}/attributes/${id}`)
        if (res.meta.status !== 200) return this.$message.error('删除参数失败')
        this.$message.success('删除参数成功')
        this.getParamsCate()
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
    // 提交参数名称的修改
    saveEditParamsCate () {
      this.$refs.editFormRef.validate(async bool => {
        if (!bool) return console.log('校验失败')
        const { data: res } = await this.$http.put(`categories/${this.cateId}/attributes/${this.editForm.attr_id}`, { attr_name: this.editForm.attr_name, attr_sel: this.activeName })
        if (res.meta.status !== 200) return this.$message.error('修改参数名称失败')
        this.$message.success('修改参数名称成功')
        this.editDialogVisible = false
        this.getParamsCate()
      })
    },
    // 关闭时清空修改对话框
    closeEditForm () {
      this.$refs.editFormRef.resetFields()
    },
    // 显示修改对话框
    showEditForm (row) {
      this.editForm = { ...row }
      this.editDialogVisible = true
    },
    // 添加分类参数
    addParamsCate () {
      this.$refs.addFormRef.validate(async bool => {
        if (!bool) return console.log('校验失败')
        const { data: res } = await this.$http.post(`categories/${this.cateId}/attributes`, { attr_sel: this.activeName, attr_name: this.addForm.attr_name })
        if (res.meta.status !== 201) return this.$message.error('添加参数失败')
        this.$message.success('添加分类成功')
        this.addDialogVisible = false
        this.getParamsCate()
      })
    },
    // 关闭添加对话框是清空对话框
    closeAddForm () {
      this.$refs.addFormRef.resetFields()
      this.addForm.attr_name = ''
    },
    // 封装 监听级联选择器函数
    async getParamsCate () {
      if (this.selectedKeys.length !== 3) {
        // 如果选中不是三级分类就清空选择项
        this.selectedKeys = []
        // 当商品分类被清空时重置tab栏中数据
        this.manyTableData = []
        this.onlyTableData = []
        return
      }
      // 获取动态参数静态属性要渲染到页面的内容
      const { data: res } = await this.$http.get(`categories/${this.cateId}/attributes`, { params: { sel: this.activeName } })
      if (res.meta.status !== 200) return this.$message.error('获取三级分类数据失败')
      // 把展开的标签数据从字符串转换成数组
      res.data.forEach(ele => {
        // 解决没有数据会显示空的tag
        ele.attr_vals = ele.attr_vals.length === 0 ? [] : ele.attr_vals.split(' ')
        // 解决操作当前输入框会同时操作其他输入框
        // 给每一个输入框都添加是否显示和value
        ele.inputVisible = false
        ele.inputValue = ''
      })
      if (this.activeName === 'many') {
        this.manyTableData = res.data
      } else {
        this.onlyTableData = res.data
      }
    },
    // tab栏切换触发函数
    handleClick () {
      this.getParamsCate()
    },
    // 级联选择器选中时触发函数
    handleChange () {
      this.getParamsCate()
    },
    // 封装 获取分类数据
    async getCateList () {
      const { data: res } = await this.$http.get('categories')
      if (res.meta.status !== 200) return this.$message.error('获取分类数据失败')
      this.cateList = res.data
    }
  },
  computed: {
    // 当选中三级分类添加按钮解除禁用
    isBtnDisabled () {
      return this.selectedKeys.length !== 3
    },
    // 选中三级分类id
    cateId () {
      return this.selectedKeys[this.selectedKeys.length - 1]
    },
    // 添加对话框的标题名
    addFormTitleName () {
      return this.activeName === 'many' ? '动态参数' : '静态属性'
    }
  },
  watch: {},
  filters: {},
  components: {},
  created () {
    this.getCateList()
  },
  mounted () { }
}
</script>

<style scoped lang='less'>
.el-tag {
  margin-right: 15px;
}

.input-new-tag {
  width: 90px;
  margin-left: 10px;
  vertical-align: bottom;
}
</style>
